package com.haiyou.common.util.stack;


import com.haiyou.common.util.string.StringFormatUitls;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: 线程堆栈打印
 * @author xingyuan
 * @date 2022年6月8日 下午2:31:48
 */
@Slf4j
public class ThreadStackUtils {

	/**
	 * 打印线程堆栈
	 * @return
	 */
	public static String printThreadStack() {
		
		StackTraceElement[] elemenets = Thread.currentThread().getStackTrace();

		StringBuffer buffer = new StringBuffer();
		
		for (int i = 2; i < elemenets.length; i++) {
			buffer.append(elemenets[i].toString()).append("\r\n");
		}
		
		return buffer.toString();
	}
	
	
	public static final String error_msg_format = "{} : {} \n";
	
	/**
	 * 基于异常输出
	 * @param e
	 * @return
	 */
	public static String printMessageAndThreadStack(Exception e) {
		
		if(e == null) {
			return "";
		}
		
		StringBuffer buffer = new StringBuffer();
		buffer.append(StringFormatUitls.format(error_msg_format, e.getClass().getName(),e.getMessage()));
		buffer.append(printThreadStack());
		return buffer.toString();
	}
	
	
	public static void main(String[] args) {
		log.info(ThreadStackUtils.printThreadStack());
	}
	
}
